package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.User;
import com.example.chamberlainserver.Service.UserService;
import com.example.chamberlainserver.Vo.Request.User.UserQuery;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public ResponseEntity<ApiResponse<User>> getUserInfo() {
        // 从SecurityContextHolder获取当前认证的用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.getUserByStuNo(username);
        
        if (user != null) {
            // 移除敏感信息
            user.setPassword(null);
            return ResponseEntity.ok(ApiResponse.success("获取用户信息成功", user));
        } else {
            return ResponseEntity.ok(ApiResponse.error(404, "用户不存在"));
        }
    }

    /**
     * 获取所有用户列表（仅管理员可访问）
     */
    @GetMapping("/list")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<User>>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        
        // 移除敏感信息
        users.forEach(user -> user.setPassword(null));
        
        return ResponseEntity.ok(ApiResponse.success("获取用户列表成功", users));
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public ResponseEntity<ApiResponse<Void>> updateUser(@RequestBody User user) {
        try {
            System.out.println("UserController.updateUser - 接收到的用户数据: " + user);
            System.out.println("UserController.updateUser - 用户ID: " + user.getId());
            System.out.println("UserController.updateUser - 用户角色: " + user.getRoles());
            
            boolean success = userService.updateUser(user);
            
            if (success) {
                System.out.println("UserController.updateUser - 更新成功");
                return ResponseEntity.ok(ApiResponse.success("更新用户信息成功", null));
            } else {
                System.out.println("UserController.updateUser - 更新失败");
                return ResponseEntity.ok(ApiResponse.error("更新用户信息失败"));
            }
        } catch (Exception e) {
            System.err.println("UserController.updateUser - 发生异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.ok(ApiResponse.error("更新用户信息失败: " + e.getMessage()));
        }
    }

    /**
     * 删除用户（仅管理员可访问）
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteUser(@PathVariable Integer id) {
        boolean success = userService.deleteUser(id);
        
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("删除用户成功", null));
        } else {
            return ResponseEntity.ok(ApiResponse.error("删除用户失败"));
        }
    }
    
    /**
     * 分页查询用户列表（仅管理员可访问）
     */
    @GetMapping("/pagedList")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<PageResult<User>>> getPagedUserList(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "userName", required = false) String userName,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "nickName", required = false) String nickName,
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "role", required = false) String role,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        try {
            UserQuery userQuery = new UserQuery();
            userQuery.setCurrent(current);
            userQuery.setPageSize(pageSize);
            userQuery.setUserName(userName);
            userQuery.setName(name);
            userQuery.setNickName(nickName);
            userQuery.setEmail(email);
            userQuery.setPhone(phone);
            userQuery.setRole(role);
            userQuery.setStatus(status);
            userQuery.setStartDate(startDate);
            userQuery.setEndDate(endDate);
            
            PageResult<User> pageResult = userService.getPagedUserList(userQuery);
            return ResponseEntity.ok(ApiResponse.success("获取用户列表成功", pageResult));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取用户列表失败: " + e.getMessage()));
        }
    }
}
